package cn.tedu._07vehicle.base.filters;

import cn.tedu._07vehicle.pojo.vo.UserVo;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = {"/v1/vehicle/*"})
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("过滤器初始化...");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.debug("过滤器销毁...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.debug("进入登录状态校验的过滤器...");
//父类中使用子类的方法,需要强转一下;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpSession session = req.getSession();
        UserVo userVo = (UserVo) session.getAttribute("userVo");
        if (userVo != null) {//已登录,放行;
            //只要有改行代码,就代表放行,如果没有该行代码,就代表拦截掉
            filterChain.doFilter(req, resp);
        }else {//未登录,重定向到登录页面
            resp.sendRedirect( "/login.html");
        }
    }
}
